const cloudHelper = require('../../../config/project_helpers_config').cloudHelper;
const pageHelper = require('../../../config/project_helpers_config').pageHelper;
const ProjectFeedbackBiz = require('../../../config/path_resolver.js').pageHelper;
const ProjectFeedbackHelper = require('../../../config/path_resolver.js').pageHelper;
const validate = require('../../../config/path_resolver.js').pageHelper;

// 使用统一配置入口导入createStoreBindings
const pathImport = require('../../../config/path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('path_import.js');
const { createStoreBindings } = pathImport;

const { feedbackStore } = require('../../../config/path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('store_config.js');

Page({
    data: {
        title: '',
        isLoad: false,
        id: '',
        formType: 'add', // add 为添加，edit 为编辑
        
        projectId: '',
        projectName: '',
        customerId: '',
        customerName: '',
        
        formTitle: '',
        formContent: '',
        formType: 1,
        formPriority: 2,
        formImages: [],
        formFiles: [],
        
        typeOptions: ProjectFeedbackHelper.TYPE_OPTIONS,
        priorityOptions: ProjectFeedbackHelper.PRIORITY_OPTIONS
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 创建MobX绑定
        this.storeBindings = createStoreBindings(this, {
            store: feedbackStore,
            fields: [
                'currentFeedback',
                'loading'
            ],
            actions: [
                'addFeedback',
                'updateFeedback',
                'setCurrentFeedback',
                'setLoading'
            ]
        });
        
        if (options && options.id) {
            this.setData({
                id: options.id,
                formType: 'edit',
                title: '编辑反馈'
            });
            this._loadDetail(options.id);
        } else {
            this.setData({
                formType: 'add',
                title: '填写反馈单',
                isLoad: true,
                formImages: [],
                formFiles: [],
                formTitle: '',
                formContent: '',
                formType: 1,
                formPriority: 2,
            });
            
            if (options && options.projectId) {
                this.setData({
                    projectId: options.projectId
                });
                
                if (options.projectName) {
                    this.setData({
                        projectName: options.projectName
                    });
                } else {
                    this._loadProjectDetail(options.projectId);
                }
            }
            
            if (options && options.customerId) {
                this.setData({
                    customerId: options.customerId
                });
                
                if (options.customerName) {
                    this.setData({
                        customerName: options.customerName
                    });
                } else {
                    this._loadCustomerDetail(options.customerId);
                }
            }
        }
    },
    
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        // 销毁MobX绑定
        if (this.storeBindings) {
            this.storeBindings.destroyStoreBindings();
        }
    },
    
    /**
     * 加载项目详情
     */
    _loadProjectDetail: async function(projectId) {
        try {
            this.setLoading(true);
            
            let params = {
                id: projectId
            };
            let opt = {
                title: '加载中'
            };
            let project = await cloudHelper.callCloudData('research_project/detail', params, opt);
            if (project) {
                this.setData({
                    projectName: project.PROJECT_NAME
                });
            }
        } catch (err) {
            console.error(err);
        } finally {
            this.setLoading(false);
        }
    },
    
    /**
     * 加载客户详情
     */
    _loadCustomerDetail: async function(customerId) {
        try {
            this.setLoading(true);
            
            let params = {
                id: customerId
            };
            let opt = {
                title: '加载中'
            };
            let customer = await cloudHelper.callCloudData('customer/detail', params, opt);
            if (customer) {
                this.setData({
                    customerName: customer.CUSTOMER_NAME
                });
            }
        } catch (err) {
            console.error(err);
        } finally {
            this.setLoading(false);
        }
    },
    
    /**
     * 加载反馈详情
     */
    _loadDetail: async function(id) {
        try {
            this.setLoading(true);
            
            let params = {
                id
            };
            let opt = {
                title: '加载中'
            };
            let feedback = await cloudHelper.callCloudData('feedback/detail', params, opt);
            if (!feedback) {
                this.setData({
                    isLoad: true
                });
                return;
            }
            
            // 设置当前反馈到MobX
            this.setCurrentFeedback(feedback);
            
            // 页面本地数据同步
            this.setData({
                isLoad: true,
                projectId: feedback.FEEDBACK_PROJECT_ID,
                projectName: feedback.PROJECT_NAME || '',
                customerId: feedback.FEEDBACK_CUSTOMER_ID,
                customerName: feedback.FEEDBACK_CUSTOMER_NAME || '',
                formTitle: feedback.FEEDBACK_TITLE,
                formContent: feedback.FEEDBACK_CONTENT,
                formType: feedback.FEEDBACK_TYPE,
                formPriority: feedback.FEEDBACK_PRIORITY,
                formImages: feedback.FEEDBACK_IMAGES || [],
                formFiles: feedback.FEEDBACK_FILES || []
            });
        } catch (err) {
            console.error(err);
        } finally {
            this.setLoading(false);
        }
    },
    
    /**
     * 表单数据保存
     */
    bindFormSubmit: async function() {
        // 数据校验
        let data = this.data;
        
        if (!data.projectId) {
            return pageHelper.showModal('请选择项目');
        }
        
        if (!data.customerId) {
            return pageHelper.showModal('请选择客户');
        }
        
        if (!data.formTitle) {
            return pageHelper.showModal('请填写反馈标题');
        }
        
        if (!data.formContent) {
            return pageHelper.showModal('请填写反馈内容');
        }
        
        let params = {
            projectId: data.projectId,
            title: data.formTitle,
            content: data.formContent,
            type: data.formType,
            priority: data.formPriority,
            customerId: data.customerId,
            customerName: data.customerName,
            images: data.formImages,
            files: data.formFiles
        };
        
        try {
            this.setLoading(true);
            
            let result;
            if (this.data.formType === 'edit') {
                // 编辑模式
                params.id = this.data.id;
                result = await cloudHelper.callCloudSumbit('feedback/update', params);
                
                // 更新MobX中的数据
                if (result && result.data) {
                    this.updateFeedback(this.data.id, result.data);
                }
            } else {
                // 添加模式
                result = await cloudHelper.callCloudSumbit('feedback/add', params);
                
                // 添加到MobX中
                if (result && result.data) {
                    this.addFeedback(result.data);
                }
            }
            
            await pageHelper.showSuccToast('提交成功', 1500);
            
            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
        } catch (err) {
            console.error(err);
        } finally {
            this.setLoading(false);
        }
    },
    
    /**
     * 表单数据变化事件
     */
    bindFormDataChange: function(e) {
        const { field } = e.currentTarget.dataset;
        this.setData({
            [`form${field}`]: e.detail.value
        });
    },
    
    /**
     * 选择项目
     */
    bindSelectProject: function() {
        wx.navigateTo({
            url: '/projects/plm/pages/project/list/project_list?back=feedback_form',
        });
    },
    
    /**
     * 选择客户
     */
    bindSelectCustomer: function() {
        wx.navigateTo({
            url: '/projects/plm/pages/customer/list/customer_list?back=feedback_form',
        });
    },
    
    /**
     * 上传图片
     */
    bindChooseImage: function() {
        wx.chooseImage({
            count: 9 - this.data.formImages.length,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: async (res) => {
                let imgsList = [];
                for (let i = 0; i < res.tempFilePaths.length; i++) {
                    let imgPath = res.tempFilePaths[i];
                    let cloudPath = ProjectFeedbackBiz.getImageCloudPath(imgPath, this.data.projectId);
                    try {
                        let res = await cloudHelper.transTempPicOne(imgPath, cloudPath);
                        imgsList.push(res.fileID);
                    } catch (err) {
                        console.error(err);
                    }
                }
                
                let formImages = this.data.formImages;
                formImages = formImages.concat(imgsList);
                this.setData({
                    formImages
                });
            }
        });
    },
    
    /**
     * 上传文件
     */
    bindChooseFile: function() {
        wx.chooseMessageFile({
            count: 5 - this.data.formFiles.length,
            type: 'file',
            success: async (res) => {
                let filesList = [];
                for (let i = 0; i < res.tempFiles.length; i++) {
                    let file = res.tempFiles[i];
                    let cloudPath = ProjectFeedbackBiz.getFileCloudPath(file.name, this.data.projectId);
                    try {
                        let res = await cloudHelper.transTempFileOne(file.path, cloudPath, file.name, file.type);
                        filesList.push({
                            url: res.fileID,
                            name: file.name,
                            type: file.type,
                            size: file.size
                        });
                    } catch (err) {
                        console.error(err);
                    }
                }
                
                let formFiles = this.data.formFiles;
                formFiles = formFiles.concat(filesList);
                this.setData({
                    formFiles
                });
            }
        });
    },
    
    /**
     * 删除图片
     */
    bindDelImage: function(e) {
        let idx = pageHelper.dataset(e, 'idx');
        let formImages = this.data.formImages;
        formImages.splice(idx, 1);
        this.setData({
            formImages
        });
    },
    
    /**
     * 删除文件
     */
    bindDelFile: function(e) {
        let idx = pageHelper.dataset(e, 'idx');
        let formFiles = this.data.formFiles;
        formFiles.splice(idx, 1);
        this.setData({
            formFiles
        });
    },
    
    /**
     * 预览图片
     */
    bindPreviewImage: function(e) {
        let url = pageHelper.dataset(e, 'url');
        let urls = this.data.formImages;
        wx.previewImage({
            current: url,
            urls
        });
    },
    
    /**
     * 预览文件
     */
    bindOpenFile: function(e) {
        let url = pageHelper.dataset(e, 'url');
        wx.showLoading({
            title: '文件打开中',
        });
        wx.openDocument({
            filePath: url,
            showMenu: true,
            success: function(res) {
                wx.hideLoading();
            },
            fail: function(err) {
                console.error(err);
                wx.hideLoading();
                pageHelper.showModal('文件打开失败');
            }
        });
    }
}); 